package com.guo.hui.service;
 
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.IOUtils;
import org.apache.cxf.io.CachedOutputStream;
import org.apache.cxf.message.Exchange;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.log4j.Logger;
 
 
public class OutMessageInterceptor extends AbstractPhaseInterceptor<Message>{
    
	private Logger log;
	 
	
	public OutMessageInterceptor(){

		this(Phase.PRE_STREAM, OutMessageInterceptor.class.getName());
	}
	
	public OutMessageInterceptor(String logName){
		
		this(Phase.PRE_STREAM, logName); 
	}
	
	protected OutMessageInterceptor(String phase, String logName)
	{
		super(phase); 
		log = Logger.getLogger(logName);
	}
	 

    protected String modifyMessage(String message)
    {
    	return message;
    }
    
	@Override
	 public void handleMessage(Message message) {
		 
        try {
 
            OutputStream os = message.getContent(OutputStream.class);
 
            CachedStream cs = new CachedStream();
            message.setContent(OutputStream.class, cs);
 
            message.getInterceptorChain().doIntercept(message);
 
            CachedOutputStream csnew = (CachedOutputStream) message.getContent(OutputStream.class);

            Exchange exchange = message.getExchange(); 
        	
        	InputStream is = csnew.getInputStream(); 
        	String xml = IOUtils.toString(is, "UTF-8");
        	
        	if (log.isInfoEnabled()) { 
        		String serviceName="";
        		if(exchange!=null && exchange.getService()!=null)
        			serviceName = exchange.getService().getName().toString();
        		log.info("Service = " + serviceName + ", soap message = " + xml);
        	 
    		}
            xml = modifyMessage(xml);
            
             
            //这里对xml做处理，处理完后同理，写回流中
            IOUtils.copy(new ByteArrayInputStream(xml.getBytes("UTF-8")), os);
            message.setContent(OutputStream.class, os);
            
            cs.close();
            os.flush();
            os.close(); 
 
 
        } catch (Exception e) {
            log.error("Error when split original inputStream. CausedBy : " + "\n" + e);
        }
    }
 
    private class CachedStream extends CachedOutputStream {
 
        public CachedStream() {
            super();
        }
 
        protected void doFlush() throws IOException {
            currentStream.flush();
        }
 
        protected void doClose() throws IOException {
        }
 
        protected void onWrite() throws IOException {
        }
 
    }
      
}
